package cn.czu.wyw.service.impl;

import cn.czu.wyw.mapper.CarouselMapper;
import cn.czu.wyw.service.ICarouselService;
import cn.czu.wyw.pojo.Carousel;
import cn.czu.wyw.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author swg.
 * @Date 2020/3/23 21:17
 * @CONTACT 317758022@qq.com
 * @DESC
 */
@Service
@Slf4j
public class CarouselServiceImpl implements ICarouselService {

    final static String DEFAULT_METRICS_PREFIX = "carousel:";

    @Autowired
    private CarouselMapper carouselMapper;

    @Autowired
    private RedisUtil redisUtil;


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Carousel> queryAll(Integer isShow) {
        log.info("查询轮播图数据列表开始，传入的参数isShow为：{}", isShow);
        List<Carousel> carousels = new ArrayList<>();
        String carouselStr = redisUtil.get(formatKey("carousel"));
        log.info("获取数据为：{}", carouselStr);
        if (StringUtils.isBlank(carouselStr)) {
            Example example = new Example(Carousel.class);
            //按照sort字段排序
            example.orderBy("sort").asc();
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("isShow", isShow);
            carousels = carouselMapper.selectByExample(example);
            redisUtil.set(formatKey("carousel"), JSON.toJSONString(carousels), 60 * 60);
        } else {
            carousels = JSON.parseObject(carouselStr, new TypeReference<List<Carousel>>() {
            });
        }
        log.info("查询轮播图数据列表结束，查询到的数据为：{}", carousels);
        return carousels;
    }

    public static String formatKey(String key){
        return DEFAULT_METRICS_PREFIX.concat(key);
    }
}
